//! 基于auxm的controller

use ane_system::dao::{SysDict, SysDictDataSimpleVo, SysDictVo};
use axum::{extract::Path, response::IntoResponse, routing::get, Extension, Router};

use crate::{
    error::{AppError, AppResult},
    extract::Json,
    state::ShareState,
};
pub mod account;
pub mod auth;
pub mod cms;
pub mod monitor;
pub mod system;

pub fn get_route<S>() -> Router<S>
where
    S: Sync + Send + Clone + 'static,
{
    Router::new().route("/dict/:dict_type", get(get_dict))
}

async fn get_dict(
    Extension(state): Extension<ShareState>,
    Path(dict_type): Path<String>,
) -> AppResult<impl IntoResponse> {
    if SysDict::fetch_dict_type::<SysDictVo>(state.db(), dict_type.clone(), Some(true))
        .await?
        .is_none()
    {
        return Err(AppError::NotFount);
    }
    let mut data = vec![];
    let mut page = 0;
    loop {
        let (total, datas) = SysDict::list_dict_data::<SysDictDataSimpleVo>(
            state.db(),
            page,
            50,
            dict_type.clone(),
            Some(true),
        )
        .await?;
        if datas.len() == 0 {
            break;
        }
        data.extend(datas);
        if total <= (data.len() as u64) {
            break;
        }
        page = page + 1;
    }
    Ok(Json(data))
}
